package com.itheima.health.controller;

import com.itheima.health.common.MessageConst;
import com.itheima.health.common.RedisConst;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Member;
import com.itheima.health.service.MemberService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.Map;

/**
 * 登录控制器
 */
@RestController
@RequestMapping("/mobile/login")
@Slf4j
public class MobileLoginController {

    @Autowired
    private MemberService memberService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/smsLogin")
    public Result login(@RequestBody Map map ){
        //获取用户手机号
        String telephone = map.get("telephone").toString();
        //获取用户提交的验证码
        String validateCode = map.get("validateCode").toString();
        //获取验证码
        String codeInRedis = (String) redisTemplate.opsForValue().get(RedisConst.VALIDATE_CODE_PREFIX+telephone);
        //判断验证码是否正确
        if (codeInRedis != null && codeInRedis.equals(validateCode)){
            //验证码正确，判断用户是否为会员
            Member member = memberService.getOneMember(telephone);
            if(member == null){
                //不是会员，注册为会员
                member = new Member();
                //设置手机号
                member.setPhoneNumber(telephone);
                //获取当前时间，为注册时间
                member.setRegTime(new Date());
                //添加会员
                memberService.saveMember(member);
            }
            //是会员，直接登录成功
            return new Result(true, MessageConst.LOGIN_SUCCESS);
        }
        //验证码错误，登录失败
        return new Result(false,MessageConst.LOGIN_FAIL);
    }

}
